import java.util.Arrays;

public class MyArrayList {
    private int[] elem;
    private int usedSize;

    private static final int DEFAULT_CAPACITY = 10;//默认容量

    public MyArrayList() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    public MyArrayList(int initCapacity) {
        this.elem = new int[initCapacity];
    }

    //打印顺序表中所有数据
    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    //是否满了
    private boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    //扩容
    private void expansion() {
        this.elem = Arrays.copyOf(this.elem, this.usedSize * 2);
    }

    //添加元素
    public void add(int data) {
        if (isFull()) {
            //扩容
            expansion();
        }
        this.elem[this.usedSize] = data;
        this.usedSize++;
    }

    //在pos位置插入一个元素
    public void add(int pos, int data) {
        if (pos < 0 || pos > this.usedSize) {
            throw new PosOutOfBoundsException(pos + " 位置不合法！");
            //System.out.println("位置不合法！");
            //return;
        }
        if (isFull()) {
            //扩容
            expansion();
        }
        for (int i = this.usedSize - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.usedSize++;
    }

    //判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    //查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    //获取pos位置的元素
    public int get(int pos) {
        if (pos < 0 || pos >= this.usedSize) {
            throw new PosOutOfBoundsException(pos + " 位置不合法！");
        }
        return this.elem[pos];
    }

    //给pos位置的元素设为value
    public void set(int pos, int value) {
        if (pos < 0 || pos >= this.usedSize) {
            throw new PosOutOfBoundsException(pos + " 位置不合法！");
        }
        this.elem[pos] = value;
    }

    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        if (!contains(toRemove)) {
            System.out.println("没有这个数据！");
            return;
        }
        for (int i = indexOf(toRemove); i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.usedSize--;
    }

    //获取顺序表长度
    public int size() {
        return this.usedSize;
    }

    //清空顺序表
    public void clear() {
        //引用类型则需全置空->null
        this.usedSize = 0;
    }
}
